package com.ruoyi.web.common.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.iot.domain.IotDataGnss;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class IOTGnssMsgUtil {

    //登录
    private static final String API_URL_LOGIN = "http://web.ims.zhdbds.com:20080/api/user/login";

    //gnss数据
    private static final String API_URL_Amnitro = "http://web.ims.zhdbds.com:20080/api/admin/posPlane/allHistoricalMonitoringData";


    private static final Map<String, String> STATION_ID_DEVICE_MAP = new HashMap<String, String>() {{
        put("16390223" ,"4208213000501");
        put("16390266" ,"4208213000502");
        put("16390176" ,"4208213000506");
        put("16390179" ,"4208213000507");
        put("16390239" ,"4208213000508");
        put("16390261" ,"4208213000509");
        put("16390242" ,"4208213000510");
        put("16390177" ,"4208213000511");
        put("16390226" ,"4208213000512");
        put("16390267" ,"4208213000513");
        put("16390238" ,"4208213000514");
        put("16390254" ,"4208213000515");
        put("16390193" ,"4208213000516");
        put("16390253" ,"4208213000517");
        put("16390216" ,"4208213000518");
        put("16390188" ,"4208213000519");
        put("16390183" ,"4208213000520");
        put("16390195" ,"4208213000503");
        put("16390271" ,"4208213000504");
        put("16390222" ,"4208213000505");
        put("16390273" ,"4208213000500");
        put("16390212" ,"4208213000599");
    }};

    private static final Map<String, String> Device_ID_DEVICE_MAP = new HashMap<String, String>() {{
        put("16390223" ,"GN0-1");
        put("16390266" ,"GN0-2");
        put("16390176" ,"GN120-1");
        put("16390179" ,"GN120-2");
        put("16390239" ,"GN120-3");
        put("16390261" ,"GN120-4");
        put("16390242" ,"GN200-1");
        put("16390177" ,"GN200-2");
        put("16390226" ,"GN200-3");
        put("16390267" ,"GN200-4");
        put("16390238" ,"GN280-1");
        put("16390254" ,"GN280-2");
        put("16390193" ,"GN280-3");
        put("16390253" ,"GN280-4");
        put("16390216" ,"GN360-1");
        put("16390188" ,"GN360-2");
        put("16390183" ,"GN360-3");
        put("16390195" ,"GN40-1");
        put("16390271" ,"GN40-2");
        put("16390222" ,"GN40-3");
        put("16390273" ,"JZ-1");
        put("16390212" ,"JZ-2");
    }};

    private static final List<String>  SNDevices = Arrays.asList(
            "16390223", "16390266", "16390176", "16390179", "16390239", "16390261",
            "16390242", "16390177", "16390226", "16390267", "16390238", "16390254", "16390193",
            "16390253", "16390216", "16390188", "16390183", "16390195", "16390271",
            "16390222", "16390273", "16390212"
    );

    private static final List<String>  STATION_IDS = Arrays.asList(
            "42073","42075","42077","42078","42079",
            "42072","42076","42083","42087","42090",
            "42071","42074","42081","42085","42089",
            "42080","42082","42084","42086","42088"

    );

//    public static JSONObject login(String url, String username, String password)
//    {
//
//        // 创建 HttpRequest 对象
//        HttpRequest request = HttpUtil.createPost(url);
//        // 设置请求体参数为 form 格式
//        request.form("user_name", username)
//                .form("password", DigestUtil.sha256Hex(password));
//        // 发送请求并获取响应
//        String response = request.execute().body();
//        // 将响应字符串解析为 JSONObject
//        JSONObject jsonObject = JSONUtil.parseObj(response);
//        return jsonObject;
//    }

    public static JSONObject login(String url, String username, String password) {
        // 创建 HttpRequest 对象
        HttpRequest request = HttpUtil.createPost(url);

        // 设置请求体参数为 JSON 格式
        JSONObject jsonParam = JSONUtil.createObj()
                .put("appid","appid")
                .put("username", username)
                .put("password", DigestUtil.sha256Hex(password));

        request.body(jsonParam.toString(), "application/json");

        // 发送请求并获取响应
        String response = request.execute().body();

        // 将响应字符串解析为 JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(response);
//        System.out.println(jsonObject);

        return jsonObject;
    }

    public static JSONObject fetchDataWithToken(String url,String token) {

        // 获取当前小时的时间范围
        String[] timeRange = getCurrentHourTimeRange();
        String startTime = timeRange[0];
        String endTime = timeRange[1];

        // 将 YCZDDevices 列表转换为逗号分隔的字符串
        String stationIds = String.join(",", STATION_IDS);
        String dynamicUrl = url +
                "?startTime=" + startTime +
                "&endTime=" + endTime +
                "&projectId=2059" +
                "&stationId=" + stationIds +
                "&sensor=L1_GP" +
                "&statsFreq=0";

        // 创建 HttpRequest 对象
        HttpRequest request = HttpUtil.createGet(dynamicUrl);
        // 添加请求头，包含 token
        request.header("Authorization",  token);

        // 发送请求并获取响应
        String response = request.execute().body();

        // 将响应字符串解析为 JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(response);

        return jsonObject;
    }

    public static List<IotDataGnss> convertUnits() {
        String token = login(API_URL_LOGIN, "yfsk", "yfsk123").get("data").toString();


        JSONObject data = fetchDataWithToken(API_URL_Amnitro,token);
//        JSONObject map = data.getByPath("data", JSONObject.class);

        List<JSONObject> list = data.getByPath("data", List.class);
        if (ObjectUtil.isEmpty( list)){
            return null;
        }
        // 使用 Stream 过滤 + 转换
        List<IotDataGnss> result = list.stream()
                .filter(item -> SNDevices.contains(item.getStr("deviceSn"))) // 排除 termiteDeviceList 中的数据
                .map(item -> {
                    IotDataGnss gnss = new IotDataGnss();
                    String deviceSn = item.getStr("deviceSn");
                    gnss.setSn(deviceSn);
                    gnss.setRemoteId(STATION_ID_DEVICE_MAP.get(deviceSn));
                    gnss.setDeviceId(Device_ID_DEVICE_MAP.get(deviceSn));
//                    String reportTime = TimeUtils.formatTimestamp(item.getStr("collectTime"));
                    gnss.setReportTime(item.getStr("collectTime"));
                    extractKeyValues(item, gnss);
                    return gnss;
                })
                .collect(Collectors.toList());


        return result;
    }

    /**
     * 从原始数据中提取keyValues并设置到IotDataGnss对象中
     *
     * @param item 原始数据对象
     * @param gnss 目标IotDataGnss对象
     */
    private static void extractKeyValues(JSONObject item, IotDataGnss gnss) {
        List<JSONObject> keyValues = item.getBeanList("keyValues", JSONObject.class);
        if (keyValues != null) {
            for (JSONObject keyValue : keyValues) {
                String key = keyValue.getStr("key");
                String value = keyValue.getStr("value");

                // 根据 key 设置对应的字段
                switch (key) {
                    case "gpsTotalZ":
                        gnss.setGpsTotalZ(value);
                        break;
                    case "displacement3d":
                        gnss.setDisplacement3d(value);
                        break;
                    case "displacement2d":
                        gnss.setDisplacement2d(value);
                        break;
                    case "gpsTotalX":
                        gnss.setGpsTotalX(value);
                        break;
                    case "gpsTotalY":
                        gnss.setGpsTotalY(value);
                        break;
                    default:
                        // 处理其他可能的键值
                        break;
                }
            }
        }
    }


    public static  Map<String, Object> convertParams(IotDataGnss gnss){
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> fields = new HashMap<>();
        fields.put("report_time", gnss.getReportTime());
        fields.put("gps_total_x", gnss.getGpsTotalX());
        fields.put("gps_total_y", gnss.getGpsTotalY());
        fields.put("gps_total_z", gnss.getGpsTotalZ());
        fields.put("displacement2d", gnss.getDisplacement2d());
        fields.put("displacement3d", gnss.getDisplacement3d());
        map.put("fields", fields);
        Map<String, Object> tags = new HashMap<>();
        tags.put("device_id", gnss.getDeviceId());
        tags.put("remote_id", gnss.getRemoteId());
        map.put("tags", tags);
        return map;
    }

    public static  Map<String, Object> convertInfluxdbParams(IotDataGnss gnss){
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> fields = new HashMap<>();
        fields.put("reportTime", gnss.getReportTime());
        fields.put("gpsTotalX", gnss.getGpsTotalX());
        fields.put("gpsTotalY", gnss.getGpsTotalY());
        fields.put("gpsTotalZ", gnss.getGpsTotalZ());
        fields.put("displacement2d", gnss.getDisplacement2d());
        fields.put("displacement3d", gnss.getDisplacement3d());
        map.put("fields", fields);
        Map<String, Object> tags = new HashMap<>();
        tags.put("deviceId", gnss.getDeviceId());
        tags.put("remoteId", gnss.getRemoteId());
        map.put("tags", tags);
        return map;
    }



    private static String[] getCurrentHourTimeRange() {
        LocalDateTime now = LocalDateTime.now();

        // 获取当前小时的开始时间
        LocalDateTime startOfHour = now.withMinute(0).withSecond(0).withNano(0);

        // 获取当前小时的结束时间
        LocalDateTime endOfHour = startOfHour.plusHours(1);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd+HH:mm:ss");

        return new String[] {
                startOfHour.format(formatter),  // 开始时间
                endOfHour.format(formatter)     // 结束时间
        };
    }


}
